package com.hokai.base.config;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.hokai.sysManage.bo.TPermissionEntiry;
import com.hokai.sysManage.bo.TRoleEntity;
import com.hokai.sysManage.bo.TUserEntity;
import com.hokai.sysManage.dao.TPermissionMapper;
import com.hokai.sysManage.dao.TRoleMapper;
import com.hokai.sysManage.service.TRoleService;
import com.hokai.sysManage.service.TUserService;
import com.hokai.utils.Page;
/*
* @ClassName: AuthRealm  
* @Description: TODO(用户token的认证和授权)  
* @author LinYing  
* @date 2018年9月14日  
 */
public class AuthRealm extends AuthorizingRealm{

	@Autowired
	private TUserService tUserService;
	
	@Autowired
	private TRoleMapper tRoleMapper;
	
	@Autowired
	private TPermissionMapper tPermissionMapper;
	
	
	/*
	 *　授权的方法是在碰到<shiro:hasPermission>标签的时候调用的,它会去检测shiro框架中的权限(这里的permissions)
	 * 是否包含有该标签的name值,如果有,里面的内容显示,如果没有,里面的内容不予显示(这就完成了对于权限的认证.)
	 * 
	 * PrincipalCollection是一个身份集合，因为我们可以在Shiro中同时配置多个Realm，所以呢身份信息可能就有多个；
	 * 因此其提供了PrincipalCollection用于聚合这些身份信息：
	 */
	//授权(角色权限和对应权限添加)
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
		// TODO Auto-generated method stub
		//获取用户名,fromRealm 根据Realm 名字（每个Principal 都与一个Realm 关联）获取相应的Principal
		TUserEntity user = (TUserEntity) principal.getPrimaryPrincipal();
		Page<TUserEntity> page=new Page<>();
		page.addParam("username", user.getName());
//		TUserEntity user = tUserService.selectByUserName(page);
		List<TRoleEntity> roles = user.getRoleEntities();
		
		SimpleAuthorizationInfo info =new SimpleAuthorizationInfo();
		System.out.println("授权 开始...");
		//获取用户名的角色信息
		if(roles!=null && roles.size()>0) {
			for(TRoleEntity role:roles) {
				info.addRole(role.getrName());
				System.err.println("授权 角色名称:"+role.getrName());
				//获取角色中的权限信息
				for(TPermissionEntiry permissionEntiry:role.getPermissionEntiries()) {
					info.addStringPermission(permissionEntiry.getName());
					System.err.println("授权 权限名称:"+permissionEntiry.getName());
				}
			}
		}
		
		return info;
	}

	
	// 认证.登录
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// TODO Auto-generated method stub
		//根据用户输入的账户信息查找有没有该用户
		UsernamePasswordToken uToken = (UsernamePasswordToken) token;
		String userName=uToken.getUsername();
		if(uToken.getUsername()==null) {
			return null;
		}
		Page<TUserEntity> page=new Page<>();
		page.addParam("username", userName);
		System.out.println("uToken.getUsername():"+uToken.getUsername());
		TUserEntity user = tUserService.selectByUserName(page);
		
		Page<TRoleEntity> page1=new Page<>();
		if(null ==user) {
			throw new UnknownAccountException();//没找到帐号
		}
		page1.addParam("userId", user.getId());
		List<TRoleEntity> roleEntities = tRoleMapper.queryIsAllotRoles(page1);
		
		List<TRoleEntity> userRoles=new ArrayList<>();
		
		if(null != roleEntities) {
			for(TRoleEntity roleEntity:roleEntities) {
				
				TRoleEntity role=new TRoleEntity();
				role=roleEntity;
				
				Page<TPermissionEntiry> page3=new Page<>();
				page3.addParam("roleId", roleEntity.getId());
				page3.addParam("type", roleEntity.getrType());
				
				List<TPermissionEntiry> permissionEntiries = tPermissionMapper.queryAllotPermissions(page3);
				if(null != permissionEntiries) {
					for(TPermissionEntiry permissionEntiry:permissionEntiries) {
						if(role.getrType().equals(permissionEntiry.getType())) {
							permissionEntiries.add(permissionEntiry);
						}
					}
					role.setPermissionEntiries(permissionEntiries);
					userRoles.add(role);
				}
			}
		}
		if(user ==null){
			throw new UnknownAccountException();//没找到帐号
		}else {
			user.setRoleEntities(userRoles);
			/*for(int i=0;i<userRoles.size();i++) {
				TRoleEntity role = userRoles.get(i);
				System.out.println("userRoleId:"+role.getId()+" userRoleName:"+role.getrName());
				List<TPermissionEntiry> permissions = role.getPermissionEntiries();
				for(int j=0;j<permissions.size();j++) {
					TPermissionEntiry permission = permissions.get(j);
					System.out.println("perId:"+permission.getId()+" perName:"+permission.getName());
				}
			}*/
			AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), getName());
			return authenticationInfo;
		}
	}

}
